package com.bsh.serviceImpl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsh.api.ApiUtils;
import com.bsh.api.Exception.ApiException;
import com.bsh.mybatis.model.Account;
import com.bsh.mybatis.model.MobileVerifyCode;
import com.bsh.mybatis.model.User;
import com.bsh.mybatis.model.UserVerifyInfo;
import com.bsh.mybatis.model.WxRecomend;
import com.bsh.repository.DaoUser;
import com.bsh.repository.DaoUserVerifyInfo;
import com.bsh.repository.DaoWxRec;
import com.bsh.service.AccountNoticeService;
import com.bsh.service.AccountService;
import com.bsh.service.ApiUserService;
import com.bsh.service.MerchantService;
import com.bsh.service.PartnerService;
import com.bsh.service.SmsService;
import com.bsh.service.UserBankService;
import com.bsh.service.UserService;
import com.bsh.service.UserVerifyService;
import com.bsh.utils.ApiMessage;
import com.bsh.utils.Constants;
import com.bsh.utils.Des3;
import com.bsh.utils.DesUtils;
import com.bsh.utils.HttpClientUtils;
import com.bsh.utils.Pager;
import com.bsh.utils.UploadUtils;
import com.mysql.jdbc.StringUtils;

@Service
public class ApiUserServiceImpl implements ApiUserService {
	private static Logger log = LoggerFactory.getLogger(ApiUserServiceImpl.class);
	@Autowired
	UserService servUser;
	@Autowired
	AccountService accountServ;
//	@Autowired
//	SmsService servSms;
	@Autowired
	AccountNoticeService accountNoticeService;
	@Autowired
	UserBankService userBankService;
	@Autowired
	UserVerifyService userVerifyService;
	@Autowired
	MerchantService merchantService;
	@Autowired
	PartnerService partnerService;
	@Autowired
	DaoUser userDao;
	@Autowired
	DaoUserVerifyInfo userVerifyDao;
	@Autowired
	DaoWxRec wxRecomend;
	
	 /**
     * 注册
     */
	/* (non-Javadoc)
	 * @see com.bsh.service.ApiUserService#register(com.alibaba.fastjson.JSONObject)
	 */
	@Override
	public ApiMessage register(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		if (ApiUtils.objIsEmpty(dto.getString("smsVerifyCode"))) {
			throw new ApiException("400", "请填写短信验证码");
		}
		if (ApiUtils.objIsEmpty(dto.getString("mobile"))) {
			throw new ApiException("400", "请填写手机号");
		}
		if (ApiUtils.objIsEmpty(dto.getString("userName"))) {
			throw new ApiException("400", "请填写用户名");
		}
		if (ApiUtils.objIsEmpty(dto.getString("password"))) {
			throw new ApiException("400", "请填写密码");
		}

		if (msg == null) {
			// 判断name 和 mobile 是否注册过
			User userCheckMobile = servUser.getUserByMobile(dto.getString("mobile"));
			if (userCheckMobile != null) {
				throw new ApiException("400", "手机号已注册过, 请登录");
			}

			User userCheckName = servUser.checkUserByNameOrMobile(dto.getString("userName"));
			if (userCheckName != null) {
				throw new ApiException("400", "用户名已注册过，请换一个");
			}

			Integer pId = null;

			if (ApiUtils.objIsNotEmpty(dto.getString("pMobile"))) {
				// 判断推荐人是否有资格 return
				User userCheckPname = servUser
						.getUserByMobile(dto.getString("pMobile"));
				if (userCheckPname == null) {
					throw new ApiException("400",  "推荐人不存在");
				}
                        

				// 20160825 郑总只有vip及以上才能推荐 -jane
				if (userCheckPname.getLevel().compareTo("comm") == 0) {
					throw new ApiException("400","该推荐人无推荐权限");
				}

				if (userCheckPname.getName().equals(dto.getString("userName"))) {
					throw new ApiException("400", "不能推荐自己");
				}

				pId = userCheckPname.getId();
			}

			// 验证手机验证码
//			Integer cacheMobileCode = servSms.getSmsCode(dto.getString("mobile"),"register");
//			if (ApiUtils.objIsEmpty(cacheMobileCode)
//					|| cacheMobileCode.equals("null")) {
//				MobileVerifyCode record = new MobileVerifyCode();
//				record.setMobile(dto.getString("mobile"));
//				record.setType("register");
//				cacheMobileCode = Integer.valueOf(servSms
//						.findCodeByMobile(record));
//			}
//
//			Integer getMobileCode = Integer.valueOf(dto.getString("smsVerifyCode"))
//					.intValue();
//			// 临时设置不变的 jane
//			// cacheMobileCode = 1234;
//			if (cacheMobileCode == null || cacheMobileCode == 0) {
//				msg = new ApiMessage("400", "手机验证码不正确，请重新发送");
//				return msg;
//			}
//			if (getMobileCode.intValue() != cacheMobileCode.intValue()) {
//				msg = new ApiMessage("400", "手机验证码不正确");
//				return msg;
//			}
			
			//缓存中取出验证码
	        String cacheVerify=String.valueOf(SmsServiceImpl.cache.Get(dto.getString("smsVerifyCode")+"register", Integer.class));
			//String cacheVerify="";
			
			String dBverify ="" ;

			if (ApiUtils.objIsEmpty(cacheVerify)
					|| cacheVerify.equals("null")) {
				MobileVerifyCode record=new MobileVerifyCode();
				record.setMobile(dto.getString("mobile"));
				record.setType("register");
				//dBverify = servSms.findCodeByMobile(record);
			}
			
			if (ApiUtils.objIsEmpty(dto.getString("smsVerifyCode"))) {
				throw new ApiException("400", "请输入验证码");
			} else if (!dto.getString("smsVerifyCode").equals(cacheVerify)&&!dto.getString("smsVerifyCode").equals(dBverify)) {
				log.error("验证码类型:"+"register"+"用户名:"+dto.getString("mobile")+"缓存:"+cacheVerify+"数据库:"+dBverify+"输入验证码:"+dto.getString("smsVerifyCode"));
				throw new ApiException("400", "验证码错误");
			}
			log.info("@@@注册---验证码类型:"+"register"+"用户名:"+dto.getString("mobile")+"缓存:"+cacheVerify+"数据库:"+dBverify+"输入验证码:"+dto.getString("smsVerifyCode"));
			User userReg = new User();
			userReg.setName(dto.getString("userName"));
			DesUtils des = new DesUtils();
			String password = des.encryptPassword(dto.getString("password"));
			userReg.setPassword(password);
			userReg.setMobile(dto.getString("mobile"));
			userReg.setPid(pId);
			userReg.setIsEffect(1);
			userReg.setIsMerchant(-1);
			userReg.setCreateTime(new Date());
			userReg.setSex(dto.getString("sex"));
			userReg.setLevel("comm"); // 默认普通会员 comm
			//添加注册信息0817
			userReg.setAppVer(dto.getString("appVer"));
			userReg.setIp(dto.getString("ip"));
			userReg.setDeviceNum(dto.getString("deviceNum"));
			userReg.setDeviceOem(dto.getString("deviceOem"));
			userReg.setDeviceOs(dto.getString("deviceOs"));
			userReg.setDeviceSize(dto.getString("deviceSize"));
			userReg.setDeviceType(dto.getString("deviceType"));
			userReg.setWxUnionid(dto.getString("wxUnionId"));
			
			//微信锁粉
			if(ApiUtils.objIsNotEmpty(dto.getString("wxUnionId"))){
				WxRecomend recordWx = new WxRecomend();
				recordWx.setUnionid(dto.getString("wxUnionId"));
				WxRecomend resWx = wxRecomend.selectByUnionIdRegister(recordWx);
				if(resWx !=null && resWx.getpMobile() != ""){
					User userWx = servUser.getUserByMobile(resWx.getpMobile());
					if(userWx !=null){
						userReg.setPid(userWx.getId());		//使用微信锁定的推荐人用户
						//以第一个人微信锁定为准
					}
				}
			}
			
			User user = servUser.registerUser(userReg);
			if (user != null) {
				Map<String, Object> userMap = new HashMap<String, Object>();
				userMap.put("id", user.getId());
				userMap.put("userName", user.getName());
				userMap.put("mobile", user.getMobile());
				userMap.put("pid", user.getPid());
				userMap.put("isMerchant", user.getIsMerchant());
				userMap.put("createTime", user.getCreateTime());
				userMap.put("isEffect", user.getIsEffect());
				userMap.put("email", user.getEmail());
				userMap.put("sex", user.getSex()); // 性别: M=男 male， F=女
													// female

				Map<String, Object> data = new HashMap<String, Object>();
				data.put("userInfo", userMap);
				data.put("token",
						ApiUtils.getToken(user.getName(), user.getPassword()));

				accountServ.newAccountByUser(user.getId());
				Map<String, Object> accInfos = new HashMap<String, Object>();
				accInfos.put("money", 0);
				accInfos.put("cloudMoney", 0);
				accInfos.put("cloudShares", 0);
				accInfos.put("cashbackMoney", "");
				accInfos.put("cashbackTime", "");
				data.put("accountInfo", accInfos);

				msg = new ApiMessage("200", "注册成功");
				msg.setData(Des3.encResponse(data));

			} else {
				throw new ApiException("102", "用户或密码错误");
			}

		}
		return msg;
	}
	/**
	 * 登录
	 */
	@Override
	public ApiMessage login(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		if (ApiUtils.objIsEmpty(dto.getString("password"))) {
			throw new ApiException("400", "请输入密码");
		}
		if (ApiUtils.objIsEmpty(dto.getString("userName"))) {
			throw new ApiException("400", "请输入用户名");
		}

		// 登录限制
//		int loginTimes = servUser.getIpLoginTimes(dto.getString("ip"));
//		if (loginTimes > Constants.IP_LOGIN_TIMES) {
//			msg = new ApiMessage("400", "登录次数超过限制");
//			return msg;
//		}

		User user = new User();
		try {
			user = servUser.login(dto.getString("userName"), dto.getString("password"));
		} catch (Exception e1) {
			throw new ApiException("400", "您的登录手机号可能关联多个用户, 请联系客服");
		}

		if (user != null) {
			if (user.getIsEffect() == null || user.getIsEffect() <= 0) {
				throw new ApiException("400", "用户未检验, 联系客服解冻");
			}

			// 0707添加信息保存
			try {
				
				user.setIp(ApiUtils.objIsNotEmpty(dto.getString("req_ip")) ? dto.getString("req_ip") : dto.getString("ip"));
				if(ApiUtils.objIsNotEmpty(dto.getString("appVer"))){
					user.setAppVer(dto.getString("appVer"));
				}
				if(ApiUtils.objIsNotEmpty(dto.getString("deviceNum"))){
					user.setDeviceNum(dto.getString("deviceNum"));
				}
				if(ApiUtils.objIsNotEmpty(dto.getString("deviceOem"))){
					user.setDeviceOem(dto.getString("deviceOem"));
				}
				if(ApiUtils.objIsNotEmpty(dto.getString("deviceOs"))){
					user.setDeviceOs(dto.getString("deviceOs"));
				}
				if(ApiUtils.objIsNotEmpty(dto.getString("deviceSize"))){
					user.setDeviceSize(dto.getString("deviceSize"));
				}
				if(ApiUtils.objIsNotEmpty(dto.getString("deviceType"))){
					user.setDeviceType(dto.getString("deviceType"));
				}
				if(ApiUtils.objIsNotEmpty(dto.getString("jpid"))){
					user.setJpid(dto.getString("jpid"));
				}
				user.setModifyTime(new Date());
				servUser.updateByPrimaryKey(user);
			} catch (Exception e) {
				log.error("保存登录信息失败" + user.getName());
			}

			Map<String, Object> userInfo = new HashMap<String, Object>();
			userInfo.put("id", user.getId());
			userInfo.put("userName", user.getName());
			userInfo.put("mobile", user.getMobile());

			// 推荐人存在判断0719
			if (user.getPid() != null && user.getPid() > 0) {
				User userPname = servUser.getUser(user.getPid());
				if (ApiUtils.objIsNotEmpty(userPname)) {
					userInfo.put("pname", userPname.getId());
				} else {
					userInfo.put("pname", user.getPid());
				}
			}
			userInfo.put("level", user.getLevel());
			int isMerchantValue = -1; // 默认-1 ：不是商家
			if (user.getIsMerchant() != null) {
				isMerchantValue = user.getIsMerchant().intValue();
			}

			userInfo.put("createTime", user.getCreateTime());
			userInfo.put("isEffect", user.getIsEffect());
			userInfo.put("email", user.getEmail());
			userInfo.put("ip", ApiUtils.objIsNotEmpty(dto.getString("req_ip")) ? dto.getString("req_ip") : dto.getString("ip"));
			userInfo.put("partnerLevel", 0);
			userInfo.put("isMerchant", isMerchantValue);
			userInfo.put("sex", user.getSex()); // 性别: M=男 male， F=女 female
			// 添加是否实名认证内容
			boolean isVerify = userVerifyService.checkUserVerify(user.getId());
			String idcard = "";
			if (isVerify) {
				idcard = userVerifyService.getUserVerify(user.getId());
			}
			userInfo.put("isVerify", isVerify);
			userInfo.put("idcard", idcard);
			// 添加头像
			String headImg = "";
			if (ApiUtils.objIsNotEmpty(user.getHeadImg())) {
				headImg=dto.getString("picUrl")+user.getHeadImg();
			}
			userInfo.put("headImg", headImg);

			// 查询是否有申请商家记录
			List<Map<String, Object>> list = merchantService.getMerchantByUserId(user.getId());
			if (list.size() > 0) {
				userInfo.put("isApplyMerchant", true);
			} else {
				userInfo.put("isApplyMerchant", false);
			}

			// 查询是否有申请商家记录
			List<Map<String, Object>> list2 = partnerService.getPartnerByUserid(user.getId());
			if (list2.size() > 0) {
				userInfo.put("isApplyPartner", true);
			} else {
				userInfo.put("isApplyPartner", false);
			}

			Map<String, Object> data = new HashMap<String, Object>();
			data.put("userInfo", userInfo);
			data.put("token", ApiUtils.getToken(user.getName(), user.getPassword()));

			Account accInfo = accountServ.getAccountByUserId(user.getId());
			if (accInfo == null) {
				String ip = ApiUtils.objIsNotEmpty(dto.getString("req_ip")) ? dto.getString("req_ip") : dto.getString("ip");
				accountServ.newAccountByUser(user.getId(), ip);
			}
			Map<String, Object> accInfos = new HashMap<String, Object>();
			accInfos.put("money", accInfo.getMoney());
			accInfos.put("cloudMoney", accInfo.getCloudMoney());
			accInfos.put("cloudShares", accInfo.getCloudShares());
			accInfos.put("cashbackMoney", "");
			accInfos.put("cashbackTime", "");
			data.put("accountInfo", accInfos);

			msg = new ApiMessage("200", "登录成功");
			msg.setData(Des3.encResponse(data));

		} else {
			throw new ApiException("102", "用户名或密码错误");
		}

		return msg;
	}
   
	
	
	

	
	@Override
	public ApiMessage changePassword(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);
		if (ApiUtils.objIsEmpty(dto.getString("password"))) {
			throw new ApiException("105", "缺少旧密码不能为空");
		}

		if (ApiUtils.objIsEmpty(dto.getString("newPassword"))) {
			throw new ApiException("105", "新密码不能为空");
		}

		// 判断是否新旧密码相同
		if (dto.getString("password").equals(dto.getString("newPassword"))) {
			throw new ApiException("106", "新旧密码不能相同");
		}

		if (ApiUtils.objIsEmpty(dto.getString("type"))) {
			throw new ApiException("105", "密码类型不能为空");
		}

		// 查询用户通过用户名
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		Account accInfo = accountServ.getAccountByUserId(user.getId());
		if (ApiUtils.objIsEmpty(accInfo)) {
			throw new ApiException("102", "账户不存在");
		}

		DesUtils des = new DesUtils();
		// 修改密码
		if ("1".equals(dto.getString("type"))) {
			// 判断密码是否正确
			if (!user.getPassword().equals(
					des.encryptPassword(dto.getString("password")))) {
				throw new ApiException("106", "密码错误");
			}
			boolean res = servUser.changePassword(user.getId(),
					dto.getString("password"), dto.getString("newPassword"));

			String msgTitle = res ? "密码修改成功" : "密码修改失败";
			msg = new ApiMessage(res ? "200" : "400", msgTitle);
			JSONObject data = new JSONObject();
			data.put("token",ApiUtils.getToken(dto.getString("userName"), dto.getString("newPassword")));
			msg.setData(data.toJSONString());

		}
		// 修改支付密码
		else if ("2".equals(dto.getString("type"))) {
			// 判断支付密码是否正确
			if (!accInfo.getPayPassword().equals(
					des.encryptPassword(dto.getString("password")))) {
				throw new ApiException("106", "支付密码错误");
			}
			accInfo.setPayPassword(des.encryptPassword(dto.getString("newPassword")));
			int res = accountServ.editAccountPassword(accInfo);
			String msgTitle = (res == -1) ? "支付密码修改失败" : "支付密码修改成功";
			msg = new ApiMessage((res == -1) ? "400" : "200", msgTitle);
		} else {
			throw new ApiException("102", "修改密码类型不存在");
		}

		return msg;
	}

	
	
	@Override
	public ApiMessage resetPassword(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		if (StringUtils.isNullOrEmpty(dto.getString("mobile"))) {
			throw new ApiException("105", "缺少手机号");
		}
		if (StringUtils.isNullOrEmpty(dto.getString("password"))) {
			throw new ApiException("105", "缺少新密码");
		}
		if (StringUtils.isNullOrEmpty(dto.getString("type"))) {
			throw new ApiException("105", "缺少重置密码类型");
		}
		//缓存中取出验证码
        String cacheVerify=String.valueOf(SmsServiceImpl.cache.Get(dto.getString("smsVerifyCode")+"register", Integer.class));
		//String cacheVerify="";
		String dBverify ="" ;

		if (ApiUtils.objIsEmpty(cacheVerify)
				|| cacheVerify.equals("null")) {
			MobileVerifyCode record = new MobileVerifyCode();
			record.setMobile(dto.getString("mobile"));
			record.setType("forgetPassword");
			//dBverify = servSms.findCodeByMobile(record);
		}

		if (StringUtils.isNullOrEmpty(dto.getString("smsVerifyCode"))) {
			throw new ApiException("400", "请输入验证码");
		} else if (!dto.getString("smsVerifyCode").equals(cacheVerify)&&!dto.getString("smsVerifyCode").equals(dBverify)) {
			log.error("重置密码验证码类型"+"forgetPassword"+"用户名:"+dto.getString("mobile")+"缓存:"+cacheVerify+"数据库:"+dBverify+"输入验证码:"+dto.getString("smsVerifyCode"));
			throw new ApiException("400", "验证码错误");
		}
		DesUtils des = new DesUtils();
		// 重置登录密码
		if ("1".equals(dto.getString("type"))) {
			boolean res = servUser.resetPassword(dto.getString("mobile"),des.encryptPassword(dto.getString("password")),dto.getString("smsVerifyCode"));
			String msgTitle = res ? "重置密码成功" : "重置密码失败";
			msg = new ApiMessage(res ? "200" : "400", msgTitle);
			JSONObject data = new JSONObject();
			data.put("token",
					ApiUtils.getToken(dto.getString("mobile"), dto.getString("password")));
			msg.setData(data.toJSONString());

		}
		// 重置支付密码
		else if ("2".equals(dto.getString("type"))) {
			String payPassword = dto.getString("password");
			User user = servUser.getUserByMobile(dto.getString("mobile"));
			if (ApiUtils.objIsEmpty(user)) {
				throw new ApiException("102", "用户不存在");
			}

			Account accInfo = accountServ.getAccountByUserId(user.getId());
			if (ApiUtils.objIsEmpty(accInfo)) {
				throw new ApiException("102", "账户不存在");
			}
			accInfo.setPayPassword(des.encryptPassword(payPassword));
			int res = accountServ.editAccountPassword(accInfo);
			String msgTitle = (res == -1) ? "重置密码失败" : "重置密码成功";
			msg = new ApiMessage((res == -1) ? "400" : "200", msgTitle);
		} else {
			throw new ApiException("102", "重置密码类型不存在");
		}
		return msg;
	}
	
	@Override
	public ApiMessage applyMerchant(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		if (StringUtils.isNullOrEmpty(dto.getString("smsVerifyCode"))) {
			throw new ApiException("400", "请填写短信验证码");
		}
		return msg;
	}
	
	
	@Override
	public ApiMessage info(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		Account accInfo = accountServ.getAccountByUserId(user.getId());
		if (ApiUtils.objIsEmpty(accInfo)) {
			throw new ApiException("102", "账户不存在");
		}
		User pidUser = servUser.getUser(user.getPid());
		String pidName = "";
		if (ApiUtils.objIsNotEmpty(pidUser)) {
			pidName = pidUser.getName();
		}
		// 查询昨日返现
		List<Map<String, Object>> yestdayMoneylist = accountNoticeService
				.getYestDayMoneyByUserid(user.getId());

		BigDecimal yestdayEarn;

		if (ApiUtils.objIsNotEmpty(yestdayMoneylist)) {
			yestdayEarn = (BigDecimal) yestdayMoneylist.get(0).get(
					"yestdayMoney");
		} else {
			yestdayEarn = new BigDecimal(0);
		}

		// 查询银行卡数量
		List<Map<String, Object>> myBankCardlist = userBankService
				.getMyBankList(user.getId());

		// 查询是否已经实名认证
		JSONObject data = new JSONObject();
		data.put("token", dto.getString("token"));// String
		data.put("name", user.getName());// string
		boolean isVerify = userVerifyService.checkUserVerify(user.getId());
		String idcard = "";
		String real_name = "";
		String sex = "";
		if (isVerify) {
			JSONObject json=userVerifyService.getUserVerifyInfo(user.getId());
			sex=json.getString("sex");
			real_name=json.getString("real_name");
			idcard=json.getString("id_card");
			data.put("sex", "M".equals(sex) ? "男" : "女");// string
			data.put("realName", real_name);// string
		}else{
			data.put("sex", "M".equals(user.getSex()) ? "男" : "女");// string
			data.put("realName", real_name);// string
		}
		// 查询会员等级
		if (ApiUtils.objIsNotEmpty(user.getLevel())) {
			if (user.getLevel().equals("comm")) {
				data.put("level", "普通会员");
			} else if (user.getLevel().equals("vip")) {
				data.put("level", "vip会员");
			} else if (user.getLevel().equals("gold")) {
				data.put("level", "金钻会员");
			}
		}

		// 查询合伙人等级
		if(ApiUtils.objIsNotEmpty(user.getPartnerLevel())){
			
			if (user.getPartnerLevel().equals((short) 1)) {
				data.put("partnerLevel", "全国合伙人");
				data.put("isPartner", 1);
			} else if (user.getPartnerLevel().equals((short) 2)) {
				data.put("partnerLevel", "省级合伙人");
				data.put("isPartner", 1);
			} else if (user.getPartnerLevel().equals((short) 3)) {
				data.put("partnerLevel", "市级合伙人");
				data.put("isPartner", 1);
			} else if (user.getPartnerLevel().equals((short) 4)) {
				data.put("partnerLevel", "县级合伙人");
				data.put("isPartner", 1);
			} 
		}else {
			data.put("partnerLevel", null);
			data.put("isPartner", 0);
		}

		// 查询是否有申请商家记录
		List<Map<String, Object>> list = merchantService
				.getMerchantByUserId(user.getId());
		if (list.size() > 0) {
			data.put("isApplyMerchant", true);
		} else {
			data.put("isApplyMerchant", false);
		}

		// 查询是否有申请合伙人记录
		List<Map<String, Object>> list2 = partnerService
				.getPartnerByUserid(user.getId());
		if (list2.size() > 0) {
			data.put("isApplyPartner", true);
		} else {
			data.put("isApplyPartner", false);
		}

		int isMerchantValue = -1; // 默认-1 ：不是商家
		if (user.getIsMerchant() != null) {
			isMerchantValue = user.getIsMerchant().intValue();
		}
		data.put("isMerchant", isMerchantValue);
		data.put("mobile", user.getMobile());// string
		// data.put("headUrl", user.getHeadImg() == null ? "" :
		// user.getHeadImg());// string
		data.put("pidName", pidName);// string
		data.put("cloudMoney", accInfo.getCloudMoney());// float
		data.put("cloudShares", accInfo.getCloudShares());// float 期权
		data.put("money", accInfo.getMoney());// float
		data.put("yestdayEarn", yestdayEarn);// float
		data.put("myBankCards", myBankCardlist.size());// int
		data.put("isVerify", isVerify); // boolean
		data.put("idcard", idcard);
		msg = new ApiMessage("200", "查询成功");
		msg.setData(data.toJSONString());
		return msg;
	}
	@Override
	public ApiMessage getUserInfo(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);

		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}

		boolean isVerify = userVerifyService.checkUserVerify(user.getId());
		JSONObject data = new JSONObject();
		data.put("isVerify", isVerify);
		String real_name = "";
		String sex = "";
		String url = "";
		if (isVerify) {
			real_name = userVerifyService.getUserVerifyInfo(user.getId())
					.getString("real_name");
			sex = userVerifyService.getUserVerifyInfo(user.getId()).getString(
					"sex");
			data.put("realName", real_name);
			data.put("sex", sex);
		} else {
			data.put("realName", user.getRealName());
			data.put("sex", user.getSex());
		}

		if (ApiUtils.objIsNotEmpty(user.getHeadImg())) {
			url = dto.getString("ip")+user.getHeadImg();
		}

		data.put("headImg", url);
		// 行业类型
		// data.put("category",
		// ApiUtils.objIsEmpty(user.getCategory())?"":user.getCategory());
		data.put("address", ApiUtils.objIsEmpty(user
				.getAddress()) ? "" : user.getAddress());
		msg = new ApiMessage("200", "用户信息查询成功");
		msg.setData(data.toString());
		return msg;

	}
	@Override
	public ApiMessage changeUserInfo(JSONObject dto,MultipartFile headPic) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		String headUrl = user.getHeadImg();
		if (ApiUtils.objIsNotEmpty(headPic)) {
			headUrl = UploadUtils.save(headPic, "/upload/private/user/headPic"
					+ user.getId());
		}
		user.setRealName(dto.getString("realName"));
		user.setSex(dto.getString("sex"));
		user.setHeadImg(headUrl);
		user.setAddress(dto.getString("address"));
		// 行业类型
		// user.setCategory(dto.getInteger("category"));
		servUser.updateByPrimaryKey(user);
		msg = new ApiMessage("200", "更新个人信息成功");
		msg.setData(headUrl);
		return msg;
	}

	@Override
	public ApiMessage authNameIdentify(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		if (ApiUtils.objIsEmpty(dto.getString("userName"))) {
			msg = new ApiMessage("105", "缺少用户名");
			return msg;
		}
		if (ApiUtils.objIsEmpty(dto.getString("token"))) {
			msg = new ApiMessage("103", "缺少token");
			return msg;
		}

		// 查询出对应的用户对象
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			msg = new ApiMessage("102", "用户或密码错误");
			return msg;
		}

		//缓存中取出验证码
        String cacheVerify=String.valueOf(SmsServiceImpl.cache.Get(dto.getString("smsVerifyCode")+"register", Integer.class));
		//String cacheVerify="";
		String dBverify = "";

		if (ApiUtils.objIsEmpty(cacheVerify)
				|| cacheVerify.equals("null")) {
			MobileVerifyCode record = new MobileVerifyCode();
			record.setMobile(user.getMobile());
			record.setType("securitySetting");
			//dBverify = servSms.findCodeByMobile(record);
		}

		if (ApiUtils.objIsEmpty(dto.getString("smsVerifyCode"))) {
			msg = new ApiMessage("400", "请输入验证码");
			return msg;
		} else if (!dto.getString("smsVerifyCode").equals(cacheVerify)
				&& !dto.getString("smsVerifyCode").equals(dBverify)) {
			log.error("实名认证验证码类型" + "securitySetting" + "用户名:"
					+ dto.getString("userName") + "缓存:" + cacheVerify + "数据库:"
					+ dBverify + "输入验证码:" + dto.getString("smsVerifyCode"));
			msg = new ApiMessage("400", "验证码错误");
			return msg;
		}

		if (ApiUtils.objIsEmpty(dto.getString("identifyName"))) {
			msg = new ApiMessage("105", "缺少认证姓名");
			return msg;
		} else if (!ApiUtils.isName(dto.getString("identifyName"))) {
			msg = new ApiMessage("102", "姓名非法");
			return msg;
		}
		if (ApiUtils.objIsEmpty(dto.getString("identifyNumber"))) {
			msg = new ApiMessage("105", "缺少持卡人身份证号");
			return msg;
		}

		//实名认证之前判断是否实名
		boolean isVerify=userVerifyService.checkUserVerify(user.getId());
		if (isVerify){
			msg = new ApiMessage("105", "您已经实名认证！");
			return msg;
		}


		String url = Constants.ID_URL + "?appkey=" + Constants.ID_API_KEY
				+ "&name=" + dto.getString("identifyName") + "&cardno="
				+ dto.getString("identifyNumber");
		try {
			String result = HttpClientUtils.executeGet(url);
			System.out.println(result);
			JSONObject jsonObj = (JSONObject) JSON.parse(result);
			if (ApiUtils.objIsEmpty(jsonObj)) {
				msg = new ApiMessage("102", "请求失败");
				return msg;
			} else if (jsonObj.getInteger("isok") == 1) {
				UserVerifyInfo uvi = new UserVerifyInfo();
				uvi.setName(dto.getString("identifyName"));
				uvi.setIdcard(dto.getString("identifyNumber"));
				JSONObject data = (JSONObject) jsonObj.get("data");
				uvi.setSex(ApiUtils.objIsEmpty(data.getString("sex")) ? "M"
						: data.getString("sex"));
				uvi.setIp(ApiUtils.objIsNotEmpty(dto.getString("req_ip")) ? dto.getString("req_ip") : dto.getString("ip"));
				uvi.setUserid(user.getId());
				uvi.setCreateTime(new Date());
				if (jsonObj.getInteger("code") == 1) {
					uvi.setIsPass((short) 1);
					msg = new ApiMessage("200", "认证成功");
					JSONObject json=new JSONObject();
					json.put("identifyName",dto.getString("identifyName") );
					json.put("identifyNumber",dto.getString("identifyNumber") );
					msg.setData(json.toJSONString());
				} else if (jsonObj.getInteger("code") == 2) {
					uvi.setIsPass((short) 0);
					msg = new ApiMessage("400", "认证失败,身份不匹配");
				} else if (jsonObj.getInteger("code") == 3) {
					uvi.setIsPass((short) 0);
					msg = new ApiMessage("400", "认证失败,无此身份证号码");
				}
				userVerifyService.saveUserVerifyInfo(uvi);
			} else if (jsonObj.getInteger("isok") == 0) {
				if (jsonObj.getInteger("code") == 11) {
					msg = new ApiMessage("400", "认证失败,参数不正确");
				} else if (jsonObj.getInteger("code") == 12) {
					msg = new ApiMessage("400", "认证失败,商户余额不足");
				} else if (jsonObj.getInteger("code") == 13) {
					msg = new ApiMessage("400", "认证失败,appkey不存在");
				} else if (jsonObj.getInteger("code") == 14) {
					msg = new ApiMessage("400", "认证失败,IP被拒绝");
				} else if (jsonObj.getInteger("code") == 20) {
					msg = new ApiMessage("400", "认证失败,身份证中心维护中");
				}
			}
		} catch (Exception e) {
			msg = new ApiMessage("400", "认证失败,请求异常");
			return msg;
		}
		return msg;
	}

	@Override
	public ApiMessage authPicIdentify(JSONObject dto) throws ApiException {
		ApiMessage msg = new ApiMessage();
		ApiUtils.checkUserNameToken(dto);
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		JSONObject result = userVerifyService.getUserVerifyInfo(user.getId());
        if(ApiUtils.objIsEmpty(result)||result.getBoolean("is_pass").equals(false)){
        	throw new ApiException("102", "请先验证身份证号");
        }
		
        if(result.getInteger("audit_status").equals("0")){
			throw new ApiException("105", "请等待审核");
        }
		
        if(result.getInteger("audit_status").equals("1")){
			throw new ApiException("105", "您已通过验证");
        }
		
		if(ApiUtils.objIsEmpty(dto.getString("pic_url"))){
			throw new ApiException("105", "请上传图片");
        }
		//保存图片验证信息
        UserVerifyInfo userVerifyInfo=new UserVerifyInfo();
        userVerifyInfo.setId(result.getInteger("id"));
        userVerifyInfo.setPicUrl(ApiUtils.removeImageUrl(dto.getString("pic_url"), dto.getString("serv_ip")));
        userVerifyInfo.setAuditStatus((short)0);
        userVerifyInfo.setAuditTime(new Date());
        userVerifyDao.updateByPrimaryKeySelective(userVerifyInfo);
        msg.setCode(Constants.REQ_SUCCESS);
        msg.setMessage(Constants.MSG_SUCCESS);
		return msg;
	}


	@Override
	public ApiMessage getMyRecMerchantList(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		Integer pageIndex = dto.getInteger("pageIndex") == null ? 1 : dto.getInteger("pageIndex");
		Integer pageSize = dto.getInteger("pageSize") == null ? 10 : dto.getInteger("pageSize");
		Pager pager = new Pager(pageIndex, pageSize);
		List<Map<String, Object>> list = servUser.getMyRecMerchantList(pager,
				user.getId());
		// 替换URL
		if (list.size() > 0) {
			String url = null;
			for (Map<String, Object> map : list) {
				url = (String) map.get("img_cover_small");
				map.remove("img_cover_small");
				map.put("img_cover_small", dto.getString("ip")+url);
			}
		}
		msg = new ApiMessage("200", "查询成功");
		JSONObject data = new JSONObject();
		data.put("myRecMerchantList", list);
		data.put("count", pager.getRowCount());
		data.put("total_page", pager.getPageCount());
		data.put("current_page", pageIndex);
		msg.setData(data.toJSONString());
		return msg;
	}
	@Override
	public ApiMessage getMyRecUserList(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		Integer pageIndex = dto.getInteger("pageIndex") == null ? 1 : dto.getInteger("pageIndex");
		Integer pageSize = dto.getInteger("pageSize") == null ? 10 : dto.getInteger("pageSize");
		Pager pager = new Pager(pageIndex, pageSize);
		List<Map<String, Object>> list = servUser.getMyRecUserList(pager,
				user.getId());
		// 替换URL
		if (list.size() > 0) {
			String url = null;
			for (Map<String, Object> map : list) {
				url = (String) map.get("head_img");
				map.remove("head_img");
				map.put("head_img", dto.getString("ip")+url);
			}
		}
		msg = new ApiMessage("200", "查询成功");
		JSONObject data = new JSONObject();
		data.put("myRecUserList", list);
		data.put("count", pager.getRowCount());
		data.put("total_page", pager.getPageCount());
		data.put("current_page", pageIndex);
		msg.setData(data.toJSONString());
		return msg;
	}
	/**
	 * 获取微信关注列表
	 */
	@Override
	public ApiMessage getWxRecList(JSONObject dto) throws ApiException {
		ApiMessage msg = null;
		ApiUtils.checkUserNameToken(dto);
		User user = servUser.getUserByName(dto.getString("userName"));
		if (ApiUtils.objIsEmpty(user)) {
			throw new ApiException("102", "用户不存在");
		}
		Integer pageIndex = dto.getInteger("pageIndex") == null ? 1 : dto.getInteger("pageIndex");
		Integer pageSize = dto.getInteger("pageSize") == null ? 10 : dto.getInteger("pageSize");
		Pager pager = new Pager(pageIndex, pageSize);
		List<Map<String, Object>> list = userDao.getWxRecList(pager, user.getMobile());
		msg = new ApiMessage("200", "查询成功");
		JSONObject data = new JSONObject();
		data.put("myWxRecList", list);
		data.put("count", pager.getRowCount());
		data.put("total_page", pager.getPageCount());
		data.put("current_page", pageIndex);
		msg.setData(data.toJSONString());
		return msg;
	}

}
